package cn.virens.common.spring.retry.annotations.handler;

import cn.virens.common.spring.annotations.VirAbstractMethodInterceptor;
import cn.virens.common.spring.retry.VirRetryException;
import cn.virens.common.util.core.Assert;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.retry.RetryException;

public class VirRetryMethodInterceptor extends VirAbstractMethodInterceptor {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    public VirRetryMethodInterceptor(VirRetryAnnotationSource annotationSource) {
        this.setAnnotationSource(Assert.isNull(annotationSource));
    }

    @Override
    protected Object invoke(MethodInvocation invocation, AnnotationAttributes attributes) throws Throwable {
        Integer retryCount = attributes.getNumber("value");

        Exception exception = null;

        while (retryCount != null && retryCount-- > 0) {
            try {
                return invocation.proceed();
            } catch (VirRetryException ex) {
                exception = ex;
            } catch (RetryException ex) {
                exception = ex;
            }
        }

        throw exception;
    }
}
